package com.empire.module.system.controller.admin.pki;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 第三方令牌核验API调用工具类（忽略SSL证书验证）
 */
@Slf4j
@Component
public class TokenVerifyApiClient {

    // 自定义配置的RestTemplate（支持忽略SSL证书）
    private RestTemplate restTemplate;

    // 目标API的请求地址
    private static final String TOKEN_VERIFY_API_URL = "https://127.0.0.1:17446/query-general-data/service";
    public static final String RESOURCE_ID_USER_VALIDATE = "/api-A-330100000000-0189-OTHER-1723539272971";
    public static final String RESOURCE_ID_APP_VALIDATE = "/api-A-330100000000-0189-OTHER-1723541877958";
    public static final String RESOURCE_ID_USER_TOKEN_INFO =     "/api-A-330100000000-0189-OTHER-1723541217058";
    public static final String RESOURCE_ID_USER_TOK_INFO =     "/api-A-330100000000-0189-OTHER-1723543810804";
    public static final String RESOURCE_ID_APP_INFO =     "/api-A-330100000000-0189-OTHER-1723542196425";

    /**
     * 调用第三方令牌核验API
     * @param appToken 应用令牌（从业务中获取真实值）
     * @param userToken 用户令牌（从业务中获取真实值）
     * @param userTokenId 待核验的用户令牌ID（核心参数）
     * @return 接口响应结果（包含status_code和message）
     */
    public TokenVerifyApiResponse callTokenVerifyApi(String appToken, String userToken, String userTokenId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON); // Content-Type: application/json
        headers.set("app_token_id", appToken); // 应用令牌请求头
        headers.set("user_token_id", userToken); // 用户令牌请求头
        headers.set("resource_id", RESOURCE_ID_USER_VALIDATE); // 资源ID（使用示例值）

        // 2. 组装请求体（仅含 userTokenId 参数）
        UserTokenVerifyApiRequest requestBody = new UserTokenVerifyApiRequest();
        requestBody.setUserTokenId(userTokenId);
        HttpEntity<UserTokenVerifyApiRequest> httpEntity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<TokenVerifyApiResponse> responseEntity = restTemplate.exchange(
                    TOKEN_VERIFY_API_URL,
                    HttpMethod.POST,
                    httpEntity,
                    TokenVerifyApiResponse.class
            );
            log.info("用户令牌核验响应：status_code=[{}], message=[{}]",
                    responseEntity.getBody().getStatus_code(), responseEntity.getBody().getMessage());
            return responseEntity.getBody();
        } catch (Exception e) {
            log.error("用户令牌核验API调用失败（appToken=[{}], userTokenId=[{}]",
                    maskSensitiveInfo(appToken), userTokenId, e);
            TokenVerifyApiResponse errorResponse = new TokenVerifyApiResponse();
            errorResponse.setStatus_code("9999");
            errorResponse.setMessage("API调用失败：" + e.getMessage());
            return errorResponse;
        }
    }

    public TokenInfoResponse getUserTokenInfo(String appToken, String userToken, String userTokenId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("app_token_id", appToken);
        headers.set("user_token_id", userToken);
        headers.set("resource_id", RESOURCE_ID_USER_TOKEN_INFO);

        log.info("发起用户令牌信息请求：appToken=[{}], userTokenId=[{}]",
                maskSensitiveInfo(appToken), userTokenId);

        UserTokenVerifyApiRequest requestBody = new UserTokenVerifyApiRequest();
        requestBody.setUserTokenId(userTokenId);
        HttpEntity<UserTokenVerifyApiRequest> httpEntity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<TokenInfoResponse> responseEntity = restTemplate.exchange(
                    TOKEN_VERIFY_API_URL,
                    HttpMethod.POST,
                    httpEntity,
                    TokenInfoResponse.class
            );
            log.info("用户令牌信息响应：status_code=[{}], pid=[{}]",
                    responseEntity.getBody().getStatus_code(),
                    responseEntity.getBody().getResult() != null ? responseEntity.getBody().getResult().getPid() : "null");
            return responseEntity.getBody();
        } catch (Exception e) {
            log.error("用户令牌信息获取失败（appToken=[{}], userTokenId=[{}]",
                    maskSensitiveInfo(appToken), userTokenId, e);
            TokenInfoResponse errorResponse = new TokenInfoResponse();
            errorResponse.setStatus_code("9999");
            errorResponse.setMessage("令牌信息获取失败：" + e.getMessage());
            return errorResponse;
        }
    }

    public TokenVerifyApiResponse verifyAppTokenApi(String appToken, String userToken, String appTokenId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("app_token_id", appToken);
        headers.set("user_token_id", userToken);
        headers.set("resource_id", RESOURCE_ID_APP_VALIDATE);

        log.info("发起应用令牌核验请求：appToken=[{}], appTokenId=[{}]",
                maskSensitiveInfo(appToken), appTokenId);

        AppTokenVerifyApiRequest requestBody = new AppTokenVerifyApiRequest();
        requestBody.setAppTokenId(appTokenId);
        HttpEntity<AppTokenVerifyApiRequest> httpEntity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<TokenVerifyApiResponse> responseEntity = restTemplate.exchange(
                    TOKEN_VERIFY_API_URL,
                    HttpMethod.POST,
                    httpEntity,
                    TokenVerifyApiResponse.class
            );
            log.info("应用令牌核验响应：status_code=[{}], message=[{}]",
                    responseEntity.getBody().getStatus_code(), responseEntity.getBody().getMessage());
            return responseEntity.getBody();
        } catch (Exception e) {
            log.error("应用令牌核验API调用失败（appToken=[{}], appTokenId=[{}]",
                    maskSensitiveInfo(appToken), appTokenId, e);
            TokenVerifyApiResponse errorResponse = new TokenVerifyApiResponse();
            errorResponse.setStatus_code("9999");
            errorResponse.setMessage("API调用失败：" + e.getMessage());
            return errorResponse;
        }
    }

    // -------------------------- 工具方法：脱敏敏感信息（避免日志泄露令牌） --------------------------
    private String maskSensitiveInfo(String info) {
        if (info == null || info.length() <= 4) {
            return "***"; // 短字符串直接脱敏
        }
        // 保留前2位和后2位，中间用*代替（如 token1234 → to**34）
        return info.substring(0, 2) + "***" + info.substring(info.length() - 2);
    }

    // -------------------------- 原有实体类保持不变 --------------------------
    @Data
    public static class UserTokenVerifyApiRequest {
        private String userTokenId;
    }

    @Data
    public static class AppTokenVerifyApiRequest {
        private String appTokenId;
    }

    @Data
    public static class TokenVerifyApiResponse {
        private String status_code;
        private String message;
    }

    @Data
    public static class TokenInfoResponse {
        private String status_code;
        private String message;
        private TokenResult result;
    }

    @Data
    public static class TokenResult {
        private String userTokenId;
        private String createTime;
        private String expireAt;
        private String pid;
        private String orgCode;
        private String ip;
        private String mid;
        private String env;
        private String sign;
    }
}
